package edu.mis.modules.resource;

import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;

import edu.mis.core.util.TreeUtil;
import edu.mis.model.Resource;

public class ResourceController extends Controller {
	public void index() {
		render("resource.html");
	}
	public void permission() {
		render("permission.html");
	}

	public void list() {
		render(new JsonRender(TreeUtil.findTree(Db.find("select * from resource where type='F'"))).forIE());//
	}

	public void add() throws Exception {
		Model<Resource> resource = getModel(Resource.class,"");
		if (resource.save()) {
			setAttr("success",true);  
			setAttr("msg","添加资源成功!");
		}else{
			setAttr("success",false);
			setAttr("msg","添加资源失败!");
		}
		renderJson();
	}
   
	public void edit() throws Exception {
		Model<Resource> resource = getModel(Resource.class,"");
		if (resource.update()) {
			setAttr("success",true);
			setAttr("msg","修改资源成功!");
		}else{
			setAttr("success",false);
			setAttr("msg","修改资源失败!");
		}
		renderJson();
	}
	
	public void delete() throws Exception {
		String ids=getPara("ids");
		if(Resource.dao.deleteBatch(ids)) {
			setAttr("success",true);
		    setAttr("msg","删除资源成功!");
		}else{
			setAttr("success",false);
			setAttr("msg","删除资源失败!");
		}
		renderJson();
	}

	/**
	 * 为下拉菜单赋值<br>
	 * Resource中菜单管理时需要使用，构建菜单树
	 */
	public void getMenu(){
		render(new JsonRender(TreeUtil.findTree(Db.find("select * from resource where type='F'"))).forIE());
	}
	
	/**
	 * 查找所有权限<br>
	 * 
	 */
	public void findAllPermission(){
		List<Record> list = Db.find("select * from resource");
		render(new JsonRender(TreeUtil.findTree(list)).forIE());
	}
	/**
	 * 获得下级权限
	 */
	public void getPermission(){
		Integer page = getParaToInt("page");
		Integer rows = getParaToInt("rows");
		String parentId = getPara("parentId");
		Page<Resource> data = Resource.dao.getPermission(page, rows,parentId);
		setAttr("rows", data.getList());	
		setAttr("total", data.getTotalRow());
		renderJson();
	}
	/**
	 * 批量更新权限
	 */
	public void addPermission(){
		int[] i=Db.batch("insert into resource(name,permCode,description,parentId,sort,type) values(?,?,?,?,?,?)", 
				new Object[][]{{"添加 ","add","拥有添加权限",getPara("pId"),"99","O"},
				{"删除 ","delete","拥有删除权限",getPara("pId"),"99","O"},
				{"修改 ","update","拥有修改权限",getPara("pId"),"99","O"},
				{"查看 ","view","拥有查看权限",getPara("pId"),"99","O"}}, 1000);
		if(i==null||i.length<0){
			setAttr("success",false);
			setAttr("msg","批量添加基本权限失败!");
		}
		renderJson();
	}
}
